package cn.tedu.luban.passport.main.controller;

import cn.tedu.luban.passport.main.service.PassportService;
import cn.tedu.luban.passport.protocol.bo.UserBO;
import cn.tedu.luban.passport.protocol.common.enums.PassportResultEnum;
import cn.tedu.luban.passport.protocol.param.UserLoginParam;
import cn.tedu.luban.passport.protocol.param.UserRegistryParam;
import cn.tedu.luban.passport.protocol.vo.LoginUserVO;
import com.tedu.inn.commons.utils.Asserts;
import com.tedu.inn.protocol.exception.BusinessException;
import com.tedu.inn.protocol.model.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@Api(
    value = "用户登录注册",
    tags = "用户登录注册"
)
public class PassportController {
    private static final String SESSION_VCODE="vcode";
    @Autowired
    private PassportService passportService;
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<LoginUserVO> doLogin(
        @RequestBody UserLoginParam userLoginParam,
        @ApiIgnore HttpServletRequest request) throws BusinessException {
        checkVcode(request,userLoginParam.getVcode());
        UserBO userBO=passportService.login(userLoginParam);
        LoginUserVO loginUserVO=new LoginUserVO();
        BeanUtils.copyProperties(userBO,loginUserVO);
        return new Result<>(loginUserVO);
    }

    /**
     * 从请求验证一下vcode是否正确
     * @param request
     */
    private void checkVcode(HttpServletRequest request,String vcode) throws BusinessException {
        HttpSession session = request.getSession();
        String sessionVcode = (String) session.getAttribute(SESSION_VCODE);
        Asserts.isTrue(StringUtils.isEmpty(vcode),new BusinessException(PassportResultEnum.EMPTY_VCODE));
        Asserts.isTrue(StringUtils.isEmpty(sessionVcode),new BusinessException(PassportResultEnum.EMPTY_SESSION_VCODE));
        Asserts.isTrue(!vcode.equalsIgnoreCase(sessionVcode),new BusinessException(PassportResultEnum.INVALID_VCODE));
        //验证没有问题后 移除当前验证码
        session.removeAttribute(SESSION_VCODE);
    }
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result<Long> doRegister(@RequestBody UserRegistryParam userParam,
        HttpServletRequest request) throws BusinessException {
        Long userId=passportService.addNewUser(userParam);
        return new Result<>(userId);
    }
}
